package com.hdoit.ares.web.acc.controllers;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.binarywang.wxpay.bean.request.WxEntPayRequest;
import com.github.binarywang.wxpay.bean.result.WxEntPayResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.hdoit.ares.logical.acc.model.WithdrawApplyfor;
import com.hdoit.ares.logical.acc.service.IWithdrawApplyforService;
import com.hdoit.ares.logical.cust.model.Customer;
import com.hdoit.ares.logical.viewmodel.acc.Withdraw;
import com.hdoit.ares.logical.viewmodel.acc.WithdrawApplyforSearch;
import com.hdoit.ares.selfcommon.utils.ExportExcel;
import com.tennetcn.common.enums.ManageContainer;
import com.tennetcn.common.enums.ModelStatus;
import com.tennetcn.common.message.PagerModel;
import com.tennetcn.common.utils.CommonUtils;
import com.tennetcn.common.utils.DateUtils;
import com.tennetcn.common.utils.RandomUtils;
import com.tennetcn.component.export.excel.ExportModel;
import com.tennetcn.component.web.ActionResult;
import com.tennetcn.component.web.BaseController;
import com.tennetcn.component.web.ErrorResult;
import com.tennetcn.component.web.JsonActionResult;
import com.tennetcn.web.cbase.wechat.WechatPayService;

/**
 * @author      caochengmeng
 * @email       
 * @createtime  2017年11月22日 10:24:52
 * @comment
 */
@Controller
@RequestMapping(value = "/admin/acc/withdrawApplyfor/")
public class WithdrawApplyforController extends BaseController{
    @Override
    public String getRoutePath() {
        return "areas/admin/acc/withdrawApplyfor/";
    }

    private IWithdrawApplyforService withdrawApplyforService;
    public IWithdrawApplyforService getWithdrawApplyforService() {
        return withdrawApplyforService;
    }
    @Resource
    public void setWithdrawApplyforService(IWithdrawApplyforService withdrawApplyforService) {
        this.withdrawApplyforService = withdrawApplyforService;
    }
    
  
    private final String indexViewName="index";
    private final String outputViewName="output";
    private final String detailedViewName="withdrawApplyforDetailed";
    private final String saveViewName="save";
    private final String deleteViewName = "delete";
    private final String toConfirmViewName = "toConfirm";
    private final String exportExcelViewName = "exportExcel";

    @RequestMapping(value = exportExcelViewName, method = { RequestMethod.GET,RequestMethod.POST })
	@ResponseBody
	public String exportExcel(WithdrawApplyforSearch withdrawApplyforSearch){
	    List<WithdrawApplyfor> withdrawApplyfors = withdrawApplyforService.queryList(withdrawApplyforSearch);
		
		ExportModel em=new ExportModel();
		
		
		em.setExcelInfoCode(ExportExcel.AllWithDrawRecordInfo);
		
		em.setDataSource(withdrawApplyfors);
		String cacheId=CommonUtils.getKeyId();
		cached.put(cacheId, em,60);
		
		return cacheId;
	}

    @RequestMapping(value = indexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String index(Model model,PagerModel pagerModel,WithdrawApplyforSearch search,boolean ajaxPost){

        pagerModel.setTotalAmount(withdrawApplyforService.queryCount(search));
        List<WithdrawApplyfor> withdrawApplyfors= withdrawApplyforService.queryList(search,pagerModel);

        model.addAttribute(ManageContainer.PAGERKEY, pagerModel);
        model.addAttribute("withdrawApplyfors", withdrawApplyfors);
        model.addAttribute("withdrawApplyforSearch", search);

        if(ajaxPost){
            return view(outputViewName);
        }

        return view(indexViewName);
    }

    @RequestMapping(value = detailedViewName, method = { RequestMethod.GET})
    public String withdrawApplyforDetailed(Model model,String key){
        WithdrawApplyfor withdrawApplyfor=new WithdrawApplyfor();
        if(!StringUtils.isEmpty(key)){
            withdrawApplyfor=withdrawApplyforService.queryModel(key);
        }
        model.addAttribute("withdrawApplyfor", withdrawApplyfor);
        return view(detailedViewName);
    }

    @RequestMapping(value = saveViewName, method = { RequestMethod.POST})
    public String save(Model model,WithdrawApplyfor withdrawApplyfor,Customer customer,Double money){
        if(StringUtils.isEmpty(withdrawApplyfor.getId())){
        	withdrawApplyfor.setCreateDate(DateUtils.getCurrent());
        	withdrawApplyfor.setId(CommonUtils.getKeyId());
        	withdrawApplyfor.setModelStatus(ModelStatus.add);
        	
        }else{
        	withdrawApplyfor.setModelStatus(ModelStatus.update);
        }

        ActionResult actionResult;
        if(withdrawApplyforService.applyChange(withdrawApplyfor)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }

        model.addAttribute("withdrawApplyfor", withdrawApplyfor);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(detailedViewName);
    }

    @RequestMapping(value =deleteViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    public @ResponseBody String delete(String key){
        if(withdrawApplyforService.deleteFakeByKey(key)){
        	
            return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }
        return new JsonActionResult(ManageContainer.ERROR).toJson();
    }
    
    
    
    
    @RequestMapping(value =toConfirmViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    @ResponseBody
    public  String toConfirm(Model model,String key,HttpServletRequest req) throws Exception{
    	Withdraw withdraw = withdrawApplyforService.updateToConfirm(key);
        if( withdraw != null){
        	WxEntPayRequest request = new WxEntPayRequest();
        	request.setOpenid(withdraw.getOpenId());
        	request.setCheckName("NO_CHECK");
        	request.setNonceStr("" + System.currentTimeMillis()+RandomUtils.randomInt(1000, 9999));
        	request.setPartnerTradeNo("" + System.currentTimeMillis()+RandomUtils.randomInt(1000, 9999));
        	request.setAmount(withdraw.getAmount());
        	request.setSpbillCreateIp("123.207.34.17");
        	request.setDescription("提现");

        	
        	
        	WxEntPayResult result = null;
        	try {
        		result = wechatPayService.entPay(request);
			} catch (WxPayException e) {
				e.printStackTrace();
			}
        	withdraw.setOutTradeNo(result.getPartnerTradeNo());
        	//根据回调结果做出相应操作
        	if(result != null && "SUCCESS".equals(result.getResultCode()) && "SUCCESS".equals(result.getReturnCode())){
        		
        		withdraw.setPaymentNo(result.getPaymentNo());
        		withdraw.setComment("提现到账成功");
        		if(withdrawApplyforService.updateGoldBeanNum(withdraw,getLoginModel())){
        			
        			return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        		}
    		}
    			
    			withdraw.setComment("提现到账失败");
    			withdrawApplyforService.updateForRollBack(withdraw,getLoginModel());

        	return new JsonActionResult(ManageContainer.ERROR).toJson();
        }
        
        return new JsonActionResult(ManageContainer.ERROR).toJson();
    }
    
    
    private WechatPayService wechatPayService;
	
	public WechatPayService getWechatPayService() {
		return wechatPayService;
	}

	@Resource
	public void setWechatPayService(WechatPayService wechatPayService) {
		this.wechatPayService = wechatPayService;
	}
    
    
   
    

   
	
}
